// 帖子详情页面功能
class PostDetail {
    constructor() {
        this.postId = this.getPostIdFromUrl();
        this.currentUser = null;
        this.post = null;
        this.comments = [];
        this.commentPage = 1;
        this.commentPageSize = 10;
        this.hasMoreComments = true;
        
        this.init();
    }

    init() {
        this.checkAuth();
        this.bindEvents();
        this.loadPost();
        this.loadComments();
    }

    getPostIdFromUrl() {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get('id');
    }

    checkAuth() {
        const token = localStorage.getItem('token');
        const user = localStorage.getItem('user');
        
        if (token && user) {
            this.currentUser = JSON.parse(user);
            this.showUserMenu();
            this.showCommentForm();
        } else {
            this.showLoginPrompt();
        }
    }

    showUserMenu() {
        document.getElementById('loginBtn').style.display = 'none';
        document.getElementById('userMenu').style.display = 'flex';
        document.getElementById('username').textContent = this.currentUser.username;
    }

    showLoginPrompt() {
        document.getElementById('loginPrompt').style.display = 'block';
        document.getElementById('commentInput').style.display = 'none';
    }

    showCommentForm() {
        document.getElementById('loginPrompt').style.display = 'none';
        document.getElementById('commentInput').style.display = 'block';
    }

    bindEvents() {
        // 登录相关
        document.getElementById('loginBtn').addEventListener('click', () => {
            document.getElementById('loginModal').style.display = 'flex';
        });

        document.getElementById('loginLink').addEventListener('click', (e) => {
            e.preventDefault();
            document.getElementById('loginModal').style.display = 'flex';
        });

        document.getElementById('logoutBtn').addEventListener('click', () => {
            this.logout();
        });

        // 模态框关闭
        document.getElementById('loginModalClose').addEventListener('click', () => {
            document.getElementById('loginModal').style.display = 'none';
        });

        document.getElementById('shareModalClose').addEventListener('click', () => {
            document.getElementById('shareModal').style.display = 'none';
        });

        // 登录表单
        document.getElementById('loginForm').addEventListener('submit', (e) => {
            this.handleLogin(e);
        });

        // 帖子操作
        document.getElementById('likeBtn').addEventListener('click', () => {
            this.toggleLike();
        });

        document.getElementById('favoriteBtn').addEventListener('click', () => {
            this.toggleFavorite();
        });

        document.getElementById('shareBtn').addEventListener('click', () => {
            document.getElementById('shareModal').style.display = 'flex';
        });

        // 评论表单
        document.getElementById('commentInput').addEventListener('submit', (e) => {
            this.handleCommentSubmit(e);
        });

        // 加载更多评论
        document.getElementById('loadMoreComments').addEventListener('click', () => {
            this.loadMoreComments();
        });

        // 分享选项
        document.querySelectorAll('.share-option').forEach(option => {
            option.addEventListener('click', (e) => {
                this.handleShare(e.currentTarget.dataset.type);
            });
        });

        // 主题切换
        document.getElementById('themeToggle').addEventListener('click', () => {
            this.toggleTheme();
        });

        // 点击模态框外部关闭
        window.addEventListener('click', (e) => {
            if (e.target.classList.contains('modal')) {
                e.target.style.display = 'none';
            }
        });
    }

    async loadPost() {
        if (!this.postId) {
            this.showError('帖子ID不存在');
            return;
        }

        try {
            const response = await fetch(`/api/v1/posts/${this.postId}`);
            
            if (!response.ok) {
                throw new Error('获取帖子失败');
            }

            const result = await response.json();
            this.post = result.data;
            this.renderPost();
        } catch (error) {
            console.error('加载帖子失败:', error);
            this.showError('加载帖子失败，请稍后重试');
        }
    }

    renderPost() {
        document.getElementById('postLoading').style.display = 'none';
        document.getElementById('postContent').style.display = 'block';

        // 设置页面标题
        document.title = `${this.post.title} - 智能博客系统`;

        // 渲染帖子内容
        document.getElementById('postTitle').textContent = this.post.title;
        document.getElementById('postAuthor').textContent = this.post.author || '匿名用户';
        document.getElementById('postDate').textContent = this.formatDate(this.post.created_at);
        document.getElementById('postCategory').textContent = this.post.category_name || '未分类';
        document.getElementById('postViews').textContent = `${this.post.views || 0} 次浏览`;
        
        // 渲染摘要
        if (this.post.summary) {
            document.getElementById('postSummary').innerHTML = `
                <h4>📝 AI 智能摘要</h4>
                <p>${this.post.summary}</p>
            `;
        } else {
            document.getElementById('postSummary').style.display = 'none';
        }

        // 渲染正文
        document.getElementById('postText').innerHTML = this.formatContent(this.post.content);

        // 渲染标签
        this.renderTags();

        // 更新点赞数
        document.getElementById('likeCount').textContent = this.post.likes || 0;
    }

    renderTags() {
        const tagsContainer = document.getElementById('postTags');
        if (this.post.tags && this.post.tags.length > 0) {
            tagsContainer.innerHTML = this.post.tags.map(tag => 
                `<a href="#" class="post-tag">#${tag}</a>`
            ).join('');
        } else {
            tagsContainer.style.display = 'none';
        }
    }

    formatContent(content) {
        // 简单的内容格式化
        return content
            .replace(/\n\n/g, '</p><p>')
            .replace(/\n/g, '<br>')
            .replace(/^/, '<p>')
            .replace(/$/, '</p>');
    }

    formatDate(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const diff = now - date;
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        
        if (days === 0) {
            const hours = Math.floor(diff / (1000 * 60 * 60));
            if (hours === 0) {
                const minutes = Math.floor(diff / (1000 * 60));
                return minutes <= 0 ? '刚刚' : `${minutes}分钟前`;
            }
            return `${hours}小时前`;
        } else if (days === 1) {
            return '昨天';
        } else if (days < 7) {
            return `${days}天前`;
        } else {
            return date.toLocaleDateString('zh-CN');
        }
    }

    async loadComments() {
        try {
            const response = await fetch(`/api/v1/posts/${this.postId}/comments?page=${this.commentPage}&page_size=${this.commentPageSize}`);
            
            if (!response.ok) {
                throw new Error('获取评论失败');
            }

            const result = await response.json();
            
            if (this.commentPage === 1) {
                this.comments = result.data || [];
            } else {
                this.comments.push(...(result.data || []));
            }

            this.hasMoreComments = result.data && result.data.length === this.commentPageSize;
            this.renderComments();
        } catch (error) {
            console.error('加载评论失败:', error);
            document.getElementById('commentsLoading').innerHTML = '<p>加载评论失败</p>';
        }
    }

    renderComments() {
        document.getElementById('commentsLoading').style.display = 'none';
        document.getElementById('commentCount').textContent = this.comments.length;

        const commentsList = document.getElementById('commentsList');
        commentsList.innerHTML = this.comments.map(comment => `
            <div class="comment-item">
                <div class="comment-header">
                    <span class="comment-author">${comment.author || '匿名用户'}</span>
                    <span class="comment-date">${this.formatDate(comment.created_at)}</span>
                </div>
                <div class="comment-content">${comment.content}</div>
                <div class="comment-actions-bar">
                    <button class="comment-action" onclick="postDetail.likeComment(${comment.id})">
                        👍 ${comment.likes || 0}
                    </button>
                    <button class="comment-action" onclick="postDetail.replyComment(${comment.id})">
                        💬 回复
                    </button>
                </div>
            </div>
        `).join('');

        // 显示/隐藏加载更多按钮
        const paginationBtn = document.getElementById('commentsPagination');
        if (this.hasMoreComments && this.comments.length > 0) {
            paginationBtn.style.display = 'block';
        } else {
            paginationBtn.style.display = 'none';
        }
    }

    async loadMoreComments() {
        this.commentPage++;
        await this.loadComments();
    }

    async handleLogin(e) {
        e.preventDefault();
        
        const username = document.getElementById('loginUsername').value;
        const password = document.getElementById('loginPassword').value;

        try {
            const response = await fetch('/api/v1/users/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            });

            const result = await response.json();

            if (response.ok) {
                localStorage.setItem('token', result.data.token);
                localStorage.setItem('user', JSON.stringify(result.data.user));
                
                this.currentUser = result.data.user;
                this.showUserMenu();
                this.showCommentForm();
                
                document.getElementById('loginModal').style.display = 'none';
                this.showNotification('登录成功', 'success');
            } else {
                this.showNotification(result.error || '登录失败', 'error');
            }
        } catch (error) {
            console.error('登录失败:', error);
            this.showNotification('登录失败，请稍后重试', 'error');
        }
    }

    logout() {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        this.currentUser = null;
        
        document.getElementById('loginBtn').style.display = 'block';
        document.getElementById('userMenu').style.display = 'none';
        this.showLoginPrompt();
        
        this.showNotification('已退出登录', 'info');
    }

    async toggleLike() {
        if (!this.currentUser) {
            this.showNotification('请先登录', 'warning');
            return;
        }

        try {
            const response = await fetch(`/api/v1/posts/${this.postId}/like`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json'
                }
            });

            if (response.ok) {
                const likeBtn = document.getElementById('likeBtn');
                const likeCount = document.getElementById('likeCount');
                
                likeBtn.classList.toggle('active');
                const currentCount = parseInt(likeCount.textContent);
                likeCount.textContent = likeBtn.classList.contains('active') ? currentCount + 1 : currentCount - 1;
                
                this.showNotification(likeBtn.classList.contains('active') ? '点赞成功' : '取消点赞', 'success');
            } else {
                this.showNotification('操作失败', 'error');
            }
        } catch (error) {
            console.error('点赞失败:', error);
            this.showNotification('操作失败，请稍后重试', 'error');
        }
    }

    async toggleFavorite() {
        if (!this.currentUser) {
            this.showNotification('请先登录', 'warning');
            return;
        }

        try {
            const response = await fetch(`/api/v1/posts/${this.postId}/favorite`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json'
                }
            });

            if (response.ok) {
                const favoriteBtn = document.getElementById('favoriteBtn');
                favoriteBtn.classList.toggle('active');
                
                const text = favoriteBtn.querySelector('.text');
                text.textContent = favoriteBtn.classList.contains('active') ? '已收藏' : '收藏';
                
                this.showNotification(favoriteBtn.classList.contains('active') ? '收藏成功' : '取消收藏', 'success');
            } else {
                this.showNotification('操作失败', 'error');
            }
        } catch (error) {
            console.error('收藏失败:', error);
            this.showNotification('操作失败，请稍后重试', 'error');
        }
    }

    async handleCommentSubmit(e) {
        e.preventDefault();
        
        const content = document.getElementById('commentText').value.trim();
        if (!content) {
            this.showNotification('请输入评论内容', 'warning');
            return;
        }

        try {
            const response = await fetch(`/api/v1/posts/${this.postId}/comments`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ content })
            });

            if (response.ok) {
                document.getElementById('commentText').value = '';
                this.commentPage = 1;
                await this.loadComments();
                this.showNotification('评论发表成功', 'success');
            } else {
                const result = await response.json();
                this.showNotification(result.error || '评论失败', 'error');
            }
        } catch (error) {
            console.error('评论失败:', error);
            this.showNotification('评论失败，请稍后重试', 'error');
        }
    }

    handleShare(type) {
        const url = window.location.href;
        const title = this.post ? this.post.title : '智能博客系统';
        
        switch (type) {
            case 'copy':
                navigator.clipboard.writeText(url).then(() => {
                    this.showNotification('链接已复制到剪贴板', 'success');
                    document.getElementById('shareModal').style.display = 'none';
                });
                break;
            case 'weibo':
                window.open(`https://service.weibo.com/share/share.php?url=${encodeURIComponent(url)}&title=${encodeURIComponent(title)}`);
                break;
            case 'wechat':
                this.showNotification('请复制链接分享到微信', 'info');
                navigator.clipboard.writeText(url);
                break;
        }
    }

    toggleTheme() {
        const body = document.body;
        const themeIcon = document.querySelector('.theme-icon');
        
        body.classList.toggle('dark-theme');
        themeIcon.textContent = body.classList.contains('dark-theme') ? '☀️' : '🌙';
        
        localStorage.setItem('theme', body.classList.contains('dark-theme') ? 'dark' : 'light');
    }

    showError(message) {
        document.getElementById('postLoading').innerHTML = `
            <div class="error-message">
                <p>❌ ${message}</p>
                <button class="btn btn-primary" onclick="location.href='index.html'">返回首页</button>
            </div>
        `;
    }

    showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.textContent = message;
        
        // 添加到页面
        document.body.appendChild(notification);
        
        // 显示动画
        setTimeout(() => notification.classList.add('show'), 100);
        
        // 自动隐藏
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => notification.remove(), 300);
        }, 3000);
    }

    async likeComment(commentId) {
        if (!this.currentUser) {
            this.showNotification('请先登录', 'warning');
            return;
        }
        
        // 实现评论点赞功能
        this.showNotification('评论点赞功能开发中', 'info');
    }

    async replyComment(commentId) {
        if (!this.currentUser) {
            this.showNotification('请先登录', 'warning');
            return;
        }
        
        // 实现评论回复功能
        this.showNotification('评论回复功能开发中', 'info');
    }
}

// 初始化主题
function initTheme() {
    const savedTheme = localStorage.getItem('theme');
    const themeIcon = document.querySelector('.theme-icon');
    
    if (savedTheme === 'dark') {
        document.body.classList.add('dark-theme');
        themeIcon.textContent = '☀️';
    } else {
        themeIcon.textContent = '🌙';
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    initTheme();
    window.postDetail = new PostDetail();
});